#-*- coding:utf-8 -*-
import sys,os
import requests
import json
import urllib

reload(sys)
sys.setdefaultencoding("utf-8")
# bugsystem="oldJira"
BASEURL={"oldJira":"http://jira.yanxiu.com","newJira":"http://newjira.yanxiu.com"}
bugsystemMap={u"GBPC":u"newJira",u"FSPC":u"newJira",u"MLS": u"newJira",u"SANKE": u"newJira",u"MES": u"newJira",u"EXEL": u"oldJira",u"XBYXGL": u"oldJira",u"XBPX":u"oldJira",u"HYFZW":u"oldJira",u"SKJC":u"oldJira",u"YTYJ":u"newJira",u"TZJSW":u"oldJira",u"PX":u"newJira",u"XCS":u"oldJira",u"YUZHONG":u"oldJira",u"WKDS":u"newJira",u"KMWH":u"newJira",u"SQ":u"newJira","LIVE":"newJira"}
class Project:
	def __init__(self,projectKey):
		self.projectKey = projectKey
		self.projectUrl = "/rest/api/2/project/" + projectKey
		url = BASEURL[bugsystemMap[projectKey]] + self.projectUrl
		response = json.loads(ApiUtils.doGet(url))
		self.projectId = response["id"]	
		#print ("project id is:"+self.projectId)
		componentsList = response["components"]
		self.versionsList=[]
		self.versionsList= response["versions"]
		self.components = []
		self.versions = {}
		for c in componentsList:
			self.components.append(c["name"])
		for v in self.versionsList:
			self.versions[v["id"]] = v["name"]

	def getVersionId(self, versionName):
		for key, value in self.versions.items():
			if value == versionName:
				return key

	def getAllVersions(self):
		url = BASEURL[bugsystemMap[self.projectKey]] + "/rest/api/2/project/" + self.projectKey
		response = json.loads(ApiUtils.doGet(url))
		return [version["name"] for version in response["versions"]]



def urlEncode(str):
	return urllib.quote(str.decode("utf-8").encode('utf8'), "()")


class ApiUtils:
	headers = {"Content-Type": "application/json", "Authorization": "Basic aG9uZ3dlaTpoMzI1NTY0NTg=",
			   "Connection": "close"}

	@staticmethod
	def doPost(self):
		pass

	@staticmethod
	def doGet(url, params=None):
		return requests.get(url, params, headers=ApiUtils.headers).text

def versionNameToVersion(projectKey,versionName):
	versions = {}
	project=Project(projectKey)
	for v in project.versionsList:
		versions[v["id"]] = v["name"]
	versions = {value: key for key, value in versions.items()}
	print "versions is ",
	print versions
	print "versions key is ",
	for key in versions.keys():
		print key
	print "##################"
	print "versionName is "
	print versionName
	version = versions[versionName]
	return version


def getBug(projectKey, version,status):
	SearchUrl = BASEURL[bugsystemMap[projectKey]] + u"/rest/api/2/search?"
	if bugsystemMap[projectKey]=="oldJira":
			version=versionNameToVersion(projectKey,version)
			print "version is ",
			print version
	if status == "all":
		basejql = u"jql=project = " + projectKey + u" AND issuetype = Bug AND affectedVersion = " + version
	elif status=="open":
		basejql = u"jql=project = " + projectKey + u" AND issuetype = Bug AND status = open AND affectedVersion = " + version
	else:
		print("status is not correct,only support open or all")
	response = json.loads(ApiUtils.doGet(SearchUrl + basejql+u"&maxResults=500"))
	bugList = response["issues"]
	Bug = []
	for bug in bugList:
		key = bug["key"]
		summary = bug["fields"]["summary"]
		try:
			assignee=bug["fields"]["assignee"]["name"]
		except Exception:
			assignee=" "
		reporter=bug["fields"]["reporter"]["name"]
		priority = bug["fields"]["priority"]["name"]
		status=bug["fields"]["status"]["name"]
		try:
			resolution=bug["fields"]["resolution"]["name"]
		except Exception:
			resolution=" "
		Bug.append((key,summary,assignee,reporter,priority,status,resolution))
	return (Bug)

def getBugDetail(projectKey,versionName):
	SearchUrl = BASEURL[bugsystemMap[projectKey]] + u"/rest/api/2/search?"
	if bugsystemMap[projectKey] == "oldJira":
		version = versionNameToVersion(projectKey,versionName)

		resolutionMap={"Fixed":u"已修复","Won'tFix":u"不修复","Duplicate":u"重复","Incomplete":u"缺详情","CannotReproduce":u"无法复现","designed":u"设计如此"}
		print ("oldJira resolutionMap is"),
		print resolutionMap

		designedJql = u"jql=project = " + projectKey + u" AND issuetype = Bug AND affectedVersion = " + version + u" AND resolution  = "+resolutionMap[u"designed"]
		res = json.loads(ApiUtils.doGet(SearchUrl + designedJql))
		designe = res["total"]
	else:
		version=versionName
		#Unresolved, Fixed, "Cannot Reproduce", "Fix In Future", "Won't Fix", Incomplete, Duplicate

		resolutionMap = {u"Unresolved": u"Unresolved", u"Fixed": u"Fixed", u"Won'tFix": u"\"Won't Fix\"", u"Duplicate": u"Duplicate",u"Incomplete": u"Incomplete", u"CannotReproduce": u"\"Cannot Reproduce\"",u"FixInFuture":u"\"Fix In Future\""}
		FixInFutureJql = u"jql=project = " + projectKey + u" AND issuetype = Bug AND affectedVersion = " + version + u" AND resolution  = "+resolutionMap[u"FixInFuture"]
		res = json.loads(ApiUtils.doGet(SearchUrl + FixInFutureJql))
		fixInFuture = res["total"]

	basejql = u"jql=project = " + projectKey + u" AND issuetype = Bug AND affectedVersion = " + version
	details = {}
	response = json.loads(ApiUtils.doGet(SearchUrl + basejql))
	total = response["total"]
	
	BlockerJql = basejql + u" AND priority  = Blocker"
	res = json.loads(ApiUtils.doGet(SearchUrl + BlockerJql))
	blocker = res["total"]
	
	criticalJql = basejql + u" AND priority  = Critical"
	res = json.loads(ApiUtils.doGet(SearchUrl + criticalJql))
	Critical=res["total"]

	majorJql = basejql + u" AND priority = Major"
	res = json.loads(ApiUtils.doGet(SearchUrl + majorJql))
	Major = res["total"]

	trivialJql= basejql + u" AND priority = Trivial"
	res = json.loads(ApiUtils.doGet(SearchUrl + trivialJql))
	Trivial = res["total"]

	minorJql = basejql + u" AND priority = Minor"
	res = json.loads(ApiUtils.doGet(SearchUrl+ minorJql))
	Minor=res["total"]

	openJql = basejql + u" AND status in (open,reopened)"
	res = json.loads(ApiUtils.doGet(SearchUrl + openJql))
	open=res["total"]

	closedJql = basejql + u" AND status = closed"
	res = json.loads(ApiUtils.doGet(SearchUrl + closedJql))
	closed=res["total"]

	otherJql = basejql + u" AND status not in (closed,open,reopened)"
	res = json.loads(ApiUtils.doGet(SearchUrl + otherJql))
	other=res["total"]

#resolution:Unresolved, Fixed, "Cannot Reproduce","Won't Fix", Incomplete, Duplicate
	unresolvedJql = basejql + u" AND resolution =Unresolved"
	res = json.loads(ApiUtils.doGet(SearchUrl + unresolvedJql))
	unresolved=res["total"]

	FixedJql = basejql + u" AND resolution ="+resolutionMap[u"Fixed"]
	res = json.loads(ApiUtils.doGet(SearchUrl + FixedJql))
	fixed=res["total"]

	CannotReproduceJql = basejql + u" AND resolution ="+resolutionMap[u"CannotReproduce"]
	res = json.loads(ApiUtils.doGet(SearchUrl + CannotReproduceJql))
	cannotReproduce=res["total"]

	WontFixdJql = basejql + u" AND resolution ="+resolutionMap[u"Won'tFix"]
	res = json.loads(ApiUtils.doGet(SearchUrl + WontFixdJql))
	wontFix=res["total"]

	IncompleteJql = basejql + u" AND resolution ="+resolutionMap[u"Incomplete"]
	res = json.loads(ApiUtils.doGet(SearchUrl + IncompleteJql))
	incomplete=res["total"]

	duplicateJql = basejql + u" AND resolution ="+resolutionMap[u"Duplicate"]
	res = json.loads(ApiUtils.doGet(SearchUrl + duplicateJql))
	duplicate=res["total"]

	if bugsystemMap[projectKey] == "oldJira":
		details = {"Jira":"oldJira","total": total,"Blocker":float(blocker)/float(total),"Critical": float(Critical)/float(total), "Major": float(Major)/float(total), "Minor": float(Minor)/float(total),"Trivial":float(Trivial)/float(total),"open": open,"closed":closed,"other":other,"unresolved": float(unresolved)/float(total),"fixed": float(fixed)/float(total),"cannotReproduce": float(cannotReproduce)/float(total),"wontFix": float(wontFix)/float(total),"incomplete": float(incomplete)/float(total),"duplicate": float(duplicate)/float(total),"designed": float(designe)/float(total)}
	else:
		details = {"Jira":"newJira","total": total,"Blocker":float(blocker)/float(total),"Critical": float(Critical)/float(total), "Major": float(Major)/float(total), "Minor": float(Minor)/float(total),"Trivial":float(Trivial)/float(total),"open": open,"closed":closed,"other":other,"unresolved": float(unresolved)/float(total),"fixed": float(fixed)/float(total),"cannotReproduce": float(cannotReproduce)/float(total),"wontFix": float(wontFix)/float(total),"incomplete": float(incomplete)/float(total),"duplicate": float(duplicate)/float(total),"fixInFuture": float(fixInFuture)/float(total)}
	return (details)

